﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Gean;
using NLog;
using Pansoft.HIME.Manager.Resources;

namespace Pansoft.HIME.Manager
{
    public class Paths
    {
        private static readonly Logger _Logger = LogManager.GetCurrentClassLogger();

        private bool _IsFirstTemp;

        private Paths()
        {
        }

        #region 单件实例

        private static readonly Lazy<Paths> _Instance = new Lazy<Paths>(() => new Paths());

        /// <summary> 获得一个本类型的单件实例.
        /// </summary>
        /// <value>The instance.</value>
        public static Paths Instance
        {
            get { return _Instance.Value; }
        }

        #endregion

        /// <summary> 存放临时文件的路径。二级目录Data/Temp
        /// </summary>
        public string TempPath
        {
            get
            {
                string path = Path.Combine(DataPath, "Temp\\");
                if (!Directory.Exists(path))
                    UtilityFile.CreateDirectory(path);
                else if (!_IsFirstTemp) //第一次使用Temp目录，清空该目录
                {
                    int i = Directory.GetFiles(path).Length;
                    if (i > 0)
                        UtilityFile.DeleteFiles(path);
                    _IsFirstTemp = true;
                }
                return path;
            }
        }

        /// <summary>根目录
        /// </summary>
        public string StartUpPath
        {
            get { return AppDomain.CurrentDomain.BaseDirectory; }
        }

        /// <summary>程序所需数据路径
        /// </summary>
        public string DataPath
        {
            get
            {
                string path = Path.Combine(StartUpPath, "Data\\");
                if (!Directory.Exists(path))
                    UtilityFile.CreateDirectory(path);
                return path;
            }
        }

        /// <summary> 一级目录
        /// </summary>
        public string ConfigPath
        {
            get
            {
                string path = Path.Combine(StartUpPath, "Config\\");
                if (!Directory.Exists(path))
                    UtilityFile.CreateDirectory(path);
                return path;
            }
        }

        /// <summary>获取程序员配置文件存放的目录
        /// </summary>
        /// <value>The coder setting path.</value>
        public string CoderSettingPath
        {
            get
            {
                string path = Path.Combine(StartUpPath, "CoderSettings\\");
                if (!Directory.Exists(path))
                    UtilityFile.CreateDirectory(path);
                return path;
            }
        }

        #region Nested type: CoderSettingFile

        public static class CoderSettingFile
        {
            private static readonly Dictionary<string, PropertyInfo> _PropeytyInfoList = new Dictionary<string, PropertyInfo>();

            static CoderSettingFile()
            {
                PropertyInfo[] propertyInfo = typeof (CoderSettingFileResource).GetProperties(BindingFlags.Static | BindingFlags.NonPublic);
                foreach (PropertyInfo info in propertyInfo)
                {
                    try
                    {
                        if (!info.Name.Contains("__"))
                            continue;
                        _PropeytyInfoList.Add(info.Name.Substring(2).ToLower(), info);
                    }
                    catch (Exception e)
                    {
                        _Logger.WarnE("CoderSetting的资源文件的属性反射异常.", e);
                    }
                }
            }

            /// <summary>
            /// 检查所有的程序员配置文件是否存在
            /// </summary>
            /// <param name="settingNames">应该有的程序员配置文件.</param>
            /// <param name="deletedNames">应该删除的程序员配置文件.</param>
            public static void Check(string[] settingNames, string[] deletedNames)
            {
                foreach (string settingName in settingNames)
                {
                    string name = string.Format("{0}{1}", settingName.ToLower(), ".codersetting");
                    _Logger.Debug(string.Format("检查配置:{0}", name));
                    string path = Path.Combine(Instance.CoderSettingPath, name);
                    if (!File.Exists(path))
                    {
                        var bt = (byte[]) _PropeytyInfoList[settingName.ToLower()].GetValue(null, null);
                        using (FileStream fs = File.Create(path))
                        {
                            fs.Write(bt, 0, bt.Length);
                            fs.Flush();
                            fs.Close();
                            fs.Dispose();
                        }
                        _Logger.Debug(string.Format("配置文件创建:{0}", name));
                    }
                    else
                    {
                        _Logger.Debug(string.Format("配置文件正常:{0}", name));
                    }
                }
                foreach (string deletedName in deletedNames)
                {
                    string name = string.Format("{0}{1}", deletedName.ToLower(), ".codersetting");
                    string path = Path.Combine(Instance.CoderSettingPath, name);
                    if (File.Exists(path))
                    {
                        _Logger.Debug(string.Format("过时的配置文件存在，将被删除{0}", name));
                        File.Delete(path);
                    }
                }
            }
        }

        #endregion
    }
}